import logging
from logging.handlers import RotatingFileHandler
import os
import datetime
import pytz


class GlobalLogger:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._configure_logger()
        return cls._instance

    def _configure_logger(self):
        """配置全局日志记录器"""
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)

        # 避免重复添加handler
        if not self.logger.handlers:
            # 控制台handler
            console_handler = logging.StreamHandler()
            console_handler.setLevel(logging.INFO)

            # 文件handler (10MB大小，保留3个备份)
            log_dir = os.path.join(os.path.dirname(__file__), "../logs")
            os.makedirs(log_dir, exist_ok=True)
            file_handler = RotatingFileHandler(
                os.path.join(
                    log_dir,
                    f"{__name__}_{self.converter(datetime.datetime.now()).strftime('%Y%m%d')}.log",
                ),
                maxBytes=10 * 1024 * 1024,
                backupCount=3,
                encoding="utf-8",
            )
            file_handler.setLevel(logging.INFO)

            # 统一格式
            formatter = logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            )
            console_handler.setFormatter(formatter)
            file_handler.setFormatter(formatter)

            self.logger.addHandler(console_handler)
            self.logger.addHandler(file_handler)

    def get_logger(self):
        return self.logger

    def converter(self, dt):
        """
        将时间转换为上海时区
        :param dt: 可以是时间戳(整数/浮点数)或datetime对象
        :return: 上海时区的datetime对象
        """
        if isinstance(dt, (int, float)):
            # 如果输入是时间戳，先转换为datetime对象
            dt = datetime.datetime.fromtimestamp(dt, tz=datetime.timezone.utc)
        elif dt.tzinfo is None:
            # 如果datetime对象没有时区信息，假设它是本地时间
            dt = dt.replace(tzinfo=datetime.timezone.utc)
        # 转换为上海时区
        return dt.astimezone(pytz.timezone("Asia/Shanghai"))


# 全局单例
logger = GlobalLogger().get_logger()
